package com.ailot.cloud.base.security.feign;

import cn.hutool.core.collection.CollUtil;
import com.ailot.cloud.base.common.constants.SecurityConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Enumeration;


/**
 * feign请求拦截器
 *
 * @author litao
 */
@Slf4j
public class BaseFeignClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("feign拦截:{}",requestTemplate.request().url());
        Collection<String> fromHeader = requestTemplate.headers().get(SecurityConstant.FROM);
        if (CollUtil.isNotEmpty(fromHeader) && fromHeader.contains(SecurityConstant.FROM_IN)) {
            return;
        }
        try {
            // 获取对象
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes();
            if (requestAttributes != null) {
                // 获取请求对象
                HttpServletRequest request = requestAttributes.getRequest();
                // 获取当前请求的header，获取到jwt令牌
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String headerName = headerNames.nextElement();
                        String headerValue = request.getHeader(headerName);
                        // 将header向下传递
                        requestTemplate.header(headerName, headerValue);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
